package com.tjc.frame;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.List;

/**
 * @Author: tjc
 * @description
 * @Date Created in 21:57 2022-08-20
 */
public class LineEncoder {
    private final Charset charset;
    private final byte[] lineSeparator;

    public LineEncoder(String lineSeparator, Charset charset) {
        this.charset = charset;
        this.lineSeparator = lineSeparator.getBytes(charset);
    }

    public void encode(CharSequence msg, List<Object> out) {
        CharBuffer src = CharBuffer.wrap(msg);
        CharsetEncoder encoder = charset.newEncoder();

        int length = (int) (src.remaining() * encoder.maxBytesPerChar()) + this.lineSeparator.length;
        ByteBuffer dstBuf = ByteBuffer.allocate(length);

        encoder.encode(src, dstBuf, true);

        dstBuf.put(this.lineSeparator);
        out.add(dstBuf);
    }


}
